<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-input
          placeholder="借款客户"
          @keyup.enter.native="getData()"
          @clear="getData()"
          clearable
          v-model="params.customer_name"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <c-select
          placeholder="客户类型"
          clearable
          number-key
          :options="enumCustomerType"
          v-model="params['org_class.eq']"
          @change="getData()"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          class="date-picker-ml"
          v-model="datePicked"
          type="daterange"
          unlink-panels
          range-separator="-"
          start-placeholder="导入时间(开始)"
          end-placeholder="导入时间(截止)"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          @change="handleDateChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item v-if="isCity">
        <select-address
          v-model="params.address_code"
          auto-top
          :bottom-level="2"
          placeholder="地址查询"
          clearable
          @change="getData()"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <select-child-bank
          clearable
          v-model="params['bank_id.eq']"
          @change="getData()"
          placeholder="导入银行(可输入过滤)"
        ></select-child-bank>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-download"
          :loading="exportLoading"
          @click="exportExcel('待提交项目')"
        >
          导出
        </el-button>
      </el-form-item>
    </el-form>

    <c-table
      v-loading="loading"
      border
      class="table-sm"
      ref="multipleTable"
      name="table"
      row-key="customer_related_id"
      :columns="tableColumns"
      :data="tableData"
      @selection-change="handleSelectionChange"
    ></c-table>

    <div class="query-pagination">
      <div class="pl-3">
        <el-checkbox
          v-model="allChecked"
          label="全选所有页"
          :disabled="loading"
          @change="handleSelectAll"
        ></el-checkbox>
        <small class="text-muted">
          (已选择
          <span class="text-info">{{ selectLen }}</span>
          个项目)
        </small>
      </div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="pageParams.index"
        :page-size="pageParams.size"
        :total="tableCount"
        @current-change="getPageData"
      ></el-pagination>
    </div>

    <div class="text-center mt-3">
      <el-button
        type="primary"
        class="btn-long"
        @click="handleConfirm"
        v-permission="{ scope: 'indoneBI' }"
      >
        提交
      </el-button>
      <el-button class="btn-long" @click="handleDismiss" v-permission="{ scope: 'indoneBI' }">
        取消
      </el-button>
    </div>

    <el-dialog
      title="项目提交"
      :visible.sync="confirmVisible"
      :close-on-click-modal="false"
      append-to-body
      width="430px"
    >
      <div class="row mb-2">
        <div class="col-4 text-right text-muted">提交数量：</div>
        <div class="col-8">{{ selectLen }} 个</div>
      </div>
      <div class="row mb-2">
        <div class="col-4 text-right text-muted">项目总额：</div>
        <div class="col-8">{{ totalFunds }} 万元</div>
      </div>
      <div class="row mb-2">
        <div class="col-4 text-right text-muted">提交日期：</div>
        <div class="col-8">{{ submitTime }}</div>
      </div>
      <template v-if="validatorData.length">
        <c-table
          v-loading="validatorLoading"
          border
          :stripe="false"
          :columns="validatorColumns"
          :row-class-name="tableRowClassName"
          :data="limitData"
        >
          <template v-slot:creno="scope">
            <span>
              {{ +scope.row.customer_type === 1 ? scope.row.register_no : scope.row.lender_idcard }}
            </span>
          </template>
        </c-table>
        <div class="query-pagination">
          <div></div>
          <el-pagination
            layout="total, prev, pager, next, jumper"
            :current-page.sync="validatorParams.index"
            :page-size="validatorParams.size"
            :total="validatorData.length"
            @current-change="getLimitData"
          ></el-pagination>
        </div>
      </template>
      <span class="text-sm text-warning" v-if="isHavelt5">
        蓝色背景的项目在保金额小于{{ +accessData.amount_min_contain === 0 ? '等于' : ''
        }}{{ +(accessData.amount_min || 0) }}万，不能提交。
      </span>
      <span class="text-sm text-warning" v-if="isHavegt1000">
        红色背景的项目在保金额已超1000万，不能再提交。
      </span>

      <div class="text-center mt-5" v-if="!isHavegt1000 && !isHavelt5">
        <el-button
          type="primary"
          class="btn-long"
          :loading="loading"
          @click="handleSubmit"
          :disabled="validatorLoading"
        >
          确认提交
        </el-button>
        <el-button
          class="btn-long"
          :loading="loading"
          :disabled="validatorLoading"
          @click="confirmVisible = false"
        >
          取消
        </el-button>
      </div>
    </el-dialog>

    <project-view-dialog
      :visible.sync="viewVisible"
      :batch-no="viewBatchNo"
      :tab-name="viewTabName"
      :query-id="viewQueryId"
    ></project-view-dialog>

    <project-back
      :import-status="importStatus"
      :visible.sync="backVisible"
      :form-data="backData"
      :table-id="backId"
      @success="handleSuccess"
    ></project-back>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { strip, dateFormat, add } from '@vimi/utils-tool'

import { lastPickerShortcuts } from '@/common/plugins/tools/date'
import { enumCustomerType, dataAdapter } from '@/bank/views/limit/index'
import hndTableMixin from '@/bank/views/business/limit/history/mixins'

import ProjectViewDialog from '@/bank/views/business/limit/new/ProjectViewDialog'
import { baseTableColumns } from '@/bank/views/business/limit/new/new/New'
import ProjectBack from '@/bank/views/business/limit/new/submit/component/ProjectBack'
import SelectAddress from '@/components/select/SelectAddress'
import SelectChildBank from '@/bank/components/select/SelectChildBank'
export default {
  components: {
    ProjectViewDialog,
    ProjectBack,
    SelectAddress,
    SelectChildBank,
  },
  mixins: [hndTableMixin],
  props: {
    visible: Boolean,
    productId: String,
  },
  data() {
    return {
      enumCustomerType,
      batchKey: 'project_apply_batch_id',

      loading: false,
      params: {
        customer_name: '',
        'org_class.eq': '',
        'review_approval.in': '0,9',
        'is_replace.neq': 1,
        'datum_status.eq': 1,
        'channel_type.eq': 1,
        'is_rural_dev.eq': 0,
      },
      pageParams: {
        index: 1,
        size: 10,
      },
      order: {
        N1create_time: 'desc',
        N2update_time: 'desc',
      },
      tableName: 'datum_one_county_industry',
      tableCount: 0,
      totalPages: 0,
      tableData: [],
      allData: [],
      tableColumns: [
        {
          attrs: {
            label: '选择',
            type: 'selection',
            align: 'center',
            width: 55,
            reserveSelection: true,
          },
        },
        ...baseTableColumns,
        {
          attrs: { label: '操作', align: 'center', minWidth: '180px' },
          operations: [
            { name: '退回', event: this.handleBack },
            { name: '拒绝', event: this.handleReject },
            { name: '查看', event: this.handleView },
            { name: '附件', event: this.handleAttach },
          ],
        },
      ],

      // 选择
      multipleSelection: [],
      allChecked: false,

      // 导入时间选择
      datePicked: [],
      pickerOptions: {
        shortcuts: lastPickerShortcuts,
      },

      // 提交
      confirmVisible: false,
      totalFunds: 0,
      totalFundsIn10To300: 0,
      submitTime: '',

      viewVisible: false,
      viewQueryId: '',
      viewTabName: 'detail',
      viewBatchNo: '',

      validatorLoading: false,
      validatorData: [],
      limitData: [],

      validatorParams: {
        index: 1,
        size: 10,
      },
      validatorColumns: [
        {
          attrs: { label: '借款客户', prop: 'customer_name', minWidth: '120px' },
          process: (v, row) => ({
            attrs: { class: 'project-history', attrs: { 'data-history': row.isSelect } },
          }),
        },
        { attrs: { label: '证件号', align: 'center' }, slot: 'creno' },
        { attrs: { label: '放款银行', align: 'center', prop: 'claim_bank_name' } },
        { attrs: { label: '在保金额', align: 'center', prop: 'warranty_amount' } },
      ],
      backVisible: false,
      backData: {},
      backId: '',
      importStatus: 2,
    }
  },
  computed: {
    ...mapGetters(['clientId', 'user', 'org', 'accessData']),
    isCity() {
      return +this.user.orgRegionLever < 3
    },
    selectLen() {
      return this.multipleSelection.length
    },
    allLen() {
      return this.allData.length
    },
    bankType() {
      return this.user.clientOrgClassType
    },
    isHavegt1000() {
      return !!this.validatorData.find(item => item.gt1000)
    },
    isHavelt5() {
      return !!this.validatorData.find(item => item.lt5)
    },
  },
  watch: {
    visible: {
      handler: function (val) {
        this.params['project_type_id.eq'] = this.productId
        if (val) {
          this.getData()
        }
      },
      immediate: true,
    },
  },
  created() {
    this.$store.dispatch('getAccessData')
  },
  mounted() {},
  methods: {
    handleSuccess() {
      this.getData()
      this.$store.dispatch('getTaskCountLimitNew', { id: this.productId })
    },
    handleReject(row = {}) {
      this.importStatus = 3
      this.backData = { ...row }
      this.backId = row?.customer_related_id ?? ''
      this.backVisible = true
    },
    handleBack(row = {}) {
      this.importStatus = 2
      this.backData = { ...row }
      this.backId = row?.customer_related_id ?? ''
      this.backVisible = true
    },
    tableRowClassName({ row }) {
      if (row?.lt5) {
        return 'bg-info'
      }
      return row?.gt1000 ? 'bg-danger' : ''
    },
    getLimitData(index = 1) {
      this.limitData = this.validatorData.slice(
        (index - 1) * this.validatorParams.size,
        index * this.validatorParams.size
      )
    },
    getData() {
      this.loading = true
      this.$api
        .getData(
          this.$serviceName,
          this.tableName,
          {
            ...this.normalParams, // 来自mixins limitNormalParams
            ...this.params,
          },
          this.order
        )
        .then(res => {
          this.allData = (res?.data ?? []).map(this.dataAdapter)
          this.tableCount = this.allLen
          this.totalPages = Math.ceil(this.tableCount / this.pageParams.size)
          this.getPageData(1)
        })
        .finally(() => {
          this.loading = false
        })
    },

    dataAdapter(item) {
      item = dataAdapter(item)
      return item
    },

    handleDateChange() {
      const [start, end] = this.datePicked || []
      if (start && end) {
        this.params['create_time.gte'] = start
        this.params['create_time.lte'] = `${end} 23:59:59`
      } else {
        this.params['create_time.gte'] = ''
        this.params['create_time.lte'] = ''
      }
      this.getData()
    },

    getPageData(index) {
      this.tableData = []
      this.pageParams.index = index
      const start = (index - 1) * this.pageParams.size
      const end = this.totalPages <= index ? this.allLen : start + this.pageParams.size
      for (let i = start; i < end; i++) {
        this.tableData.push(this.allData[i])
      }
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
      this.allChecked = this.selectLen === this.allLen
    },

    // 全选
    handleSelectAll(val) {
      const $tableRef = this.$refs.multipleTable.$refs.table
      if (!$tableRef) return

      if (val) {
        $tableRef.store.states.selection = this.allData.slice()
        $tableRef.$emit('selection-change', this.allData.slice())
        $tableRef.store.updateAllSelected()
      } else {
        $tableRef.clearSelection()
      }
    },

    clearSelect() {
      const $tableRef = this.$refs.multipleTable.$refs.table
      if (!$tableRef) return
      $tableRef.clearSelection()
    },

    reset() {
      this.multipleSelection = []
      this.allChecked = false
      this.clearSelect()
    },

    handleView(row = {}) {
      this.viewQueryId = row.customer_related_id
      this.viewBatchNo = row[this.batchKey]
      this.viewTabName = 'detail'
      this.viewVisible = true
    },

    handleAttach(row = {}) {
      this.viewQueryId = row.customer_related_id
      this.viewBatchNo = row[this.batchKey]
      this.viewTabName = 'attach'
      this.viewVisible = true
    },

    handleConfirm() {
      if (!this.selectLen) {
        return this.$message.error(this.tableData.length ? '请先选择提交项目' : '暂无可提交的项目')
      }

      // 项目总额
      let totalFunds = 0
      let totalFundsIn10To300 = 0
      for (const project of this.multipleSelection) {
        const funds = +project.warranty_amount || 0
        totalFunds += funds
        if (funds >= 10 && funds <= 300) {
          totalFundsIn10To300 += funds
        }
      }
      this.totalFunds = strip(totalFunds)
      this.totalFundsIn10To300 = strip(totalFundsIn10To300)

      // 提交日期
      this.submitTime = dateFormat(new Date(), 'yyyy年MM月dd日')
      this.toValidator300()
      this.confirmVisible = true
    },
    toValidator300() {
      const idTemp = this.multipleSelection.filter(
        item => +item.customer_type === 2 && !!item.lender_idcard
      )
      const idObject = idTemp.reduce((a, i) => {
        if (a[i.lender_idcard]) {
          a[i.lender_idcard].push({ ...i })
        } else {
          a[i.lender_idcard] = [{ ...i }]
        }
        return a
      }, {})

      const registerTemp = this.multipleSelection.filter(
        item => +item.customer_type === 1 && !!item.register_no
      )
      const registerObject = registerTemp.reduce((a, i) => {
        if (a[i.register_no]) {
          a[i.register_no].push({ ...i })
        } else {
          a[i.register_no] = [{ ...i }]
        }
        return a
      }, {})
      const idCards = idTemp.map(item => item.lender_idcard)
      const registerNos = registerTemp.map(item => item.register_no)
      const len = 200
      const count = Math.ceil(idCards.length / len)
      const registerCount = Math.ceil(registerNos.length / len)
      const promiseAll = []
      const idData = []
      const registerData = []
      for (let i = 0; i < count; i++) {
        const idString = idCards.slice(i * len, (i + 1) * len).join(',')
        promiseAll.push(
          this.$api
            .getData(this.$serviceName, 'customer_left_funds_view_28', {
              isBIQuery: 1,
              'customer_type.eq': 2,
              'lender_idcard.in': idString,
            })
            .then(res => {
              if (res && res.data && res.data.length) {
                idData.push(...res.data)
              }
            })
        )
      }

      for (let i = 0; i < registerCount; i++) {
        const registString = registerNos.slice(i * len, (i + 1) * len).join(',')
        promiseAll.push(
          this.$api
            .getData(this.$serviceName, 'customer_left_funds_view_28', {
              isBIQuery: 1,
              'customer_type.eq': 1,
              'register_no.in': registString,
            })
            .then(res => {
              if (res && res.data && res.data.length) {
                registerData.push(...res.data)
              }
            })
        )
      }
      this.validatorLoading = true
      Promise.all(promiseAll)
        .then(() => {
          idData.forEach(item => {
            if (idObject[item.lender_idcard]) {
              idObject[item.lender_idcard].push({ ...item, isSelect: 1 })
            }
          })
          registerData.forEach(item => {
            if (registerObject[item.register_no]) {
              registerObject[item.register_no].push({ ...item, isSelect: 1 })
            }
          })

          this.validatorData = []
          Object.keys(idObject).forEach(id => {
            const num = idObject[id].reduce((num, i) => {
              return add(num, i.warranty_amount)
            }, 0)
            if (
              +num < +(this.accessData.amount_min || 0) ||
              (+this.accessData.amount_min_contain === 0 &&
                +num === +(this.accessData.amount_min || 0))
            ) {
              this.validatorData.unshift(
                ...idObject[id].map(item => {
                  item.lt5 = true
                  return item
                })
              )
            } else if (num > 1000) {
              this.validatorData.unshift(
                ...idObject[id].map(item => {
                  item.gt1000 = true
                  return item
                })
              )
            } else if (num > 300) {
              this.validatorData.push(...idObject[id])
            }
          })
          Object.keys(registerObject).forEach(id => {
            const num = registerObject[id].reduce((num, i) => {
              return add(num, i.warranty_amount)
            }, 0)
            if (
              +num < +(this.accessData.amount_min || 0) ||
              (+this.accessData.amount_min_contain === 0 &&
                +num === +(this.accessData.amount_min || 0))
            ) {
              this.validatorData.unshift(
                ...registerObject[id].map(item => {
                  item.lt5 = true
                  return item
                })
              )
            } else if (num > 1000) {
              this.validatorData.unshift(
                ...registerObject[id].map(item => {
                  item.gt1000 = true
                  return item
                })
              )
            } else if (num > 300) {
              this.validatorData.push(...registerObject[id])
            }
          })
          this.getLimitData()
        })
        .catch(() => {
          this.loading = true
        })
        .finally(() => {
          this.validatorLoading = false
        })
    },
    handleSubmit() {
      const {
        user: { userId, realName },
        org: { orgName },
        clientId,
        selectLen,
        totalFunds,
        totalFundsIn10To300,
        bankType,
      } = this
      const masterTable = 'project_apply_batch'
      const slaveTable = 'project_apply_batch_detail'

      const masterData = {
        project_count: selectLen,
        project_funds: totalFunds,
        '10_300_funds': totalFundsIn10To300,
        submit_client_id: clientId,
        submit_client_name: orgName,
        submit_person: userId,
        submit_person_name: realName,
        bank_type: bankType,
        channel_type: 1,
        is_rural_dev: 0,
      }
      const slaveData = this.multipleSelection.map(it => ({
        customer_related_id: it.customer_related_id,
        submit_person: userId,
        submit_person_name: realName,
        update_person: userId,
      }))
      const formData = {
        masterTableInfo: JSON.stringify(masterData),
        masterTableName: masterTable,
        slaveTableInfo: JSON.stringify(slaveData),
        slaveTableName: slaveTable,
      }

      // 关联添加
      this.loading = true
      this.$api
        .relatedBatch(this.$serviceName, formData)
        .then(res => {
          this.$message.success('提交成功！')
          this.confirmVisible = false
          this.$emit('success', res)
          this.handleDismiss()
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description ?? '提交失败，请重试！')
        })
        .finally(() => {
          this.loading = false
        })
    },

    handleDismiss(e) {
      this.reset()
      this.$emit('dismiss', e)
    },
  },
}
</script>

<style lang="scss" scoped></style>
